package com.wenhuang.chatgptopen.controller;

import com.wenhuang.chatgptopen.pojo.User;
import com.wenhuang.chatgptopen.retu.RegisterReturn;
import com.wenhuang.chatgptopen.service.UserService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/*
 *@Time：2023/5/20
 *@Author：Jelly
 */
@Controller
public class RegisterController {

    @Autowired
    private UserService userService;
    private RegisterReturn registerReturn;

    //注册页面的业务,接收注册信息，加入到数据库中
    @PostMapping("/register")
    @ResponseBody
    public RegisterReturn register(User user, HttpServletResponse response) {

        System.out.println(user);
        //初始化registerReturn
        registerReturn = new RegisterReturn();
        //定义message
        String message = "";
        //定义result
        String result = "fail";
        try {
            /**
             * 先判断邮箱、用户名、密码是否为空
             */
            if ("".equals(user.getEmail())) {
                message = "邮箱不能为空";
            } else if ("".equals(user.getPassword())) {
                message = "密码不能为空";
            } else if ("".equals(user.getUsername())) {
                message = "用户名不能为空";
            } else {
                //都不为空则开始进行验证
                //先对需要注册的邮箱验证是否存在
                if ((userService.verifyEmail(user)) != null) {
                    //说明邮箱已经注册过了
                    message = "该邮箱已被注册，请点击登录";
                } else {
                    //说明邮箱未被注册过
                    if ((userService.addUser(user)) != null) {
                        //注册成功
                        message = "success";
                        result = "success";
                    } else {
                        message = "注册失败";
                    }
                }
            }
        } catch (Exception e) {
            response.setStatus(401);
        }
        registerReturn.setResult(result);
        registerReturn.setMessage(message);
        return registerReturn;
    }
}